﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Betop.Lib.Core.Config;
using Betop.Lib.Core.Register;
using Betop.Lib.Core.Company;
using Betop.Lib.Utilities;

namespace Betop.Lib.Core.Cache
{
    public class CacheLoader
    {
        private Action<CacheContainer> _loadComplete;

        public CacheLoader(Action<CacheContainer> loadComplete)
        {
            _loadComplete = loadComplete;

            LoadData();
        }


        public void Update()
        {
            Thread thread = new Thread(() =>
            {
                LoadData();
            });

            thread.IsBackground = true;
            thread.Start();
        }

        private void LoadData()
        {
            CacheContainer container = new CacheContainer();

            SysConfigBO cfg = new SysConfigBO();
            List<SysConfigInfo> list = cfg.GetList();

            container.SysConfigs = new Dictionary<string, SysConfigInfo>();

            foreach (SysConfigInfo info in list)
            {
                container.SysConfigs.Add(info.ID, info);
            }
            if (container.SysConfigs.ContainsKey(ConfigID.reginfo.ToString()))
            {
                container.RegisterInfo = (RegisterInfo)Serialize.BinaryDeserialize(container.SysConfigs[ConfigID.reginfo.ToString()].Config);
            }
            else
            {
                container.RegisterInfo = new RegisterInfo();
            }


            CompanyBO company = new CompanyBO();
            List<CompanyInfo> coms = company.GetList();
            container.ConnectionStrings = new Dictionary<int, string>();
            foreach (CompanyInfo info in coms)
            {
                container.ConnectionStrings.Add(info.ID, info.ConnectionString);
            }



            _loadComplete(container);
        }

    }
}
